package com.thinkit.cms.controller.admin;

import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.thinkit.cms.api.admin.AnalysisService;
import com.thinkit.cms.dto.admin.AnalysisDto;
import com.thinkit.core.base.BaseController;
import com.thinkit.utils.model.PageDto;
import com.thinkit.utils.utils.Checker;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.io.IOException;

/**
 * <p>
 * 流量统计配置 前端控制器
 * </p>
 *
 * @author lg
 * @since 2020-11-25
 */
@Validated
@RestController
@RequestMapping("analysis")
public class AnalysisController extends BaseController<AnalysisService> {


    @GetMapping("getByPk")
    public AnalysisDto get(@NotBlank @RequestParam String id){
       return  service.getByPk(id);
    }

    @PostMapping(value="save")
    public void save(@Validated @RequestBody AnalysisDto v){
        service.insert(v);
    }

    @PutMapping("update")
    public void update(@RequestBody AnalysisDto v){
        service.updateByPk(v);
    }

    @DeleteMapping("deleteByPk")
    public boolean deleteByPk(@NotBlank @RequestParam String id) {
         return service.deleteByPk(id);
    }


    @PostMapping("page")
    public PageDto<AnalysisDto> listPage(@RequestBody PageDto<AnalysisDto> pageDto){
        return service.listPage(pageDto);
    }


    @GetMapping("view")
    public void goToBaiDuTj(HttpServletRequest request,HttpServletResponse response, String id) throws IOException {
        AnalysisDto analysisDto = service.getByPk(id);
        if(Checker.BeNotNull(analysisDto)){
            String uaStr = request.getHeader("user-agent");
            UserAgent ua = UserAgentUtil.parse(uaStr);
            if(ua.isMobile()){
                String url =Checker.BeNotBlank(analysisDto.getMobileUrl())?analysisDto.getMobileUrl():analysisDto.getPcUrl();
                response.sendRedirect(url);
            }else{
                response.sendRedirect(analysisDto.getPcUrl());
            }
        }
    }

}
